let fs = require('fs');
let path = require('path');

/**单层目录可以控制是否删除跟目录
 * 多层目录如果控制不删除根目录，会所有目录都不删除
 */
function delDir(dirPath,isdeleteRoot){
	let files = [];
	if(fs.existsSync(dirPath)){
		files = fs.readdirSync(dirPath);
		for(let i=0;i<files.length;i++){
			let file = files[i];
			let curPath = path.join(dirPath,file);
			if(fs.statSync(curPath).isDirectory()){
				delDir(curPath,isdeleteRoot); 
			} else {
				fs.unlinkSync(curPath); 
			}
		}
		isdeleteRoot&&fs.rmdirSync(dirPath);
	}
}
/**
 * 遍历某个目录
 * @param {*} srcPath 某个目录
 * @param {*} callBack 如果是文件的话，回调，参数是：文件路径，文件的文件夹路径，文件名
 */
function walkSync(srcPath,callBack){
	fs.readdirSync(srcPath).forEach(function(name){
		let filePath = path.join(srcPath,name);
		let stat = fs.statSync(filePath);
		if (stat.isFile()) {
			callBack(filePath,srcPath,name);
		} else if (stat.isDirectory()) {
			walkSync(filePath, callBack);
		}
	});
}
/**递归创建目录 同步方法 */
function mkdirsSync(dirname) {
	if (fs.existsSync(dirname)) {
		return true;
	} else {
		if (mkdirsSync(path.dirname(dirname))) {
			fs.mkdirSync(dirname);
			return true;
		}
	}
}

exports.delDir = delDir;
exports.walkSync = walkSync;
exports.mkdirsSync = mkdirsSync;